package cn.slipi.pan.common.exception;

import cn.slipi.pan.common.constants.ExceptionConstants;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

/**
 * 服务异常
 */
@Getter
public class ServiceException extends RuntimeException {
    /**
     * 错误码
     */
    private final int code;
    /**
     * 异常消息
     */
    private final String message;

    public ServiceException(int code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public static ServiceException create(ExceptionConstants constant) {
        return new ServiceException(constant.getCode(), constant.getMessage());
    }

    public static ServiceException create(ExceptionConstants constant, Object... params) {
        return new ServiceException(constant.getCode(), format(constant.getMessage(), params));
    }

    /**
     * 字符串格式化
     *
     * @param template
     * @param params
     * @return
     */
    public static String format(String template, Object[] params) {
        if (StringUtils.isEmpty(template) || null == params || params.length == 0) {
            return template;
        }
        String result = template;
        for (Object param : params) {
            int index = result.indexOf("{}");
            if (index == -1) {
                return result;
            }
            result = result.substring(0, index) + param + result.substring(index + 2);
        }
        return result;
    }
}
